package com.lantosec.hmrp.modules.form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.Result;
import com.lantosec.hmrp.core.util.BeanUtils;
import com.lantosec.hmrp.modules.form.entity.FormLayout;
import com.lantosec.hmrp.modules.form.mapper.FormLayoutMapper;
import com.lantosec.hmrp.modules.form.service.IFormLayoutService;
import com.lantosec.hmrp.modules.form.vo.FormLayoutVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自定义表单布局 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-04-15
 */
@Service
@Primary
@Log4j2
public class FormLayoutServiceImpl extends ServiceImpl<FormLayoutMapper, FormLayout> implements IFormLayoutService {

    @Override
    public List<FormLayoutVO> queryByTableId(String tableId) {
        if(StringUtils.isBlank(tableId)){
            return null;
        }
        List<FormLayout> list = baseMapper.selectList(new QueryWrapper<FormLayout>()
                .eq(String.valueOf(FormLayout.ColName.table_id), tableId)
                .orderByDesc(String.valueOf(FormLayout.ColName.create_date))
        );

        List<FormLayoutVO> listVO = BeanUtils.entity2VO(list);
        //TABLE 表格， FORM 表单
        listVO.forEach(item->{item.setLayoutType("FORM");});
        return listVO;
    }

    @Override
    public Result<String> saveLayout(FormLayout entity) {
        if (isExist(entity)) {
            return Result.fail("表单布局名称已经存在");
        }
        // 只能添加扩展字段
        entity.setCreateDate(new Date());

        boolean flag = super.save(entity);
        if(!flag) {
            return Result.fail("保存失败");
        }
        return Result.ok(entity.getLayoutId());
    }

    @Override
    public Result<Void> updateLayout(FormLayout entity) {
        if (isExist(entity)) {
            return Result.fail("表单布局名称已经存在");
        }
        boolean flag = super.updateById(entity);
        if(!flag) {
            return Result.fail("保存失败");
        }
        return Result.ok();
    }

    /**
     * 同一表单不能有相同的布局名称
     *
     * @param entity
     * @return
     */
    private boolean isExist(FormLayout entity) {
        Integer count = baseMapper.selectCount(new QueryWrapper<FormLayout>()
                .notIn(StringUtils.isNotBlank(entity.getLayoutId()), String.valueOf(FormLayout.ColName.layout_id), entity.getLayoutId())
                .eq(String.valueOf(FormLayout.ColName.table_id), entity.getTableId())
                .eq(String.valueOf(FormLayout.ColName.layout_name), entity.getLayoutName()));
        return count > 0;
    }

}
